﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xc.DataAccess.Core;
using Xc.DataAccess.HyperTerminalCore.Models;
using Xc.HyperTerminal.ViewModels;
using Xc.Logics.HyperTerminalCore.Tcp.Views;

namespace Xc.HyperTerminal.Services
{
    internal class DataHandler
    {
        TcpClientInfo tcpClientInfo;
        private readonly TerminalView OnMessage;
        public DataHandler(TcpClientInfo tcpClientInfo, TerminalView onMessage)
        {
            this.tcpClientInfo = tcpClientInfo;
            this.OnMessage = onMessage;
        }
        /// <summary>
        /// 发起请求
        /// </summary>
        /// <param name="command"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public async Task Request(string command,FileStream fileStream,Func<string, TcpClientInfo, DataHandler, ChatInfo,FileStream, Task> filter)
        {
            var res = await  OnMessage.Send(command);
            if (res)
            {
#if DEBUG
                int time = 8000;
#else
                int time = 3000;
#endif
                var dd =  await tcpClientInfo.ReadDataByTemplate<ChatInfo>(time, (data) => 
                {
                    var msg = Encoding.UTF8.GetString(data);
                    if (!msg.Contains("\n"))
                    {
                        return ResultData< ChatInfo>.Reject("还没有结束",default);
                    }
                    var text = msg;
                    var c = new ViewModels.ChatInfo { DateTime = DateTime.Now, Alignment = System.Windows.HorizontalAlignment.Left, Content = text, Status = ViewModels.Status.Success };
                    OnMessage.AddLog(c);
                    filter?.Invoke(text, tcpClientInfo, this, c, fileStream);
                    return ResultData<ChatInfo>.Accept("还没有结束", c);
                });
                if (dd.IsError)
                {
                    dd.Data.RespondMessage = "设备无响应";
                }
            }
        }
    }
}
